package com.wodan.zhongjinjicang.common.orm.utils;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;

import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 保存运行时间的集合
 * 
 * @ClassName: ExecTimeRecordCollection
 * @author Administrator
 * @date 2015-7-24 下午8:49:39
 * @history
 * 
 */
@Service
public class ExecTimeRecordCollection implements DebugSupport {
	private final LoadingCache<String, ConcurrentMap<String, ExecTimeRecord>> debugInfoCache = CacheBuilder
			.newBuilder().build(new CacheLoader<String, ConcurrentMap<String, ExecTimeRecord>>() {
				@Override
				public ConcurrentMap<String, ExecTimeRecord> load(String key) throws Exception {
					return Maps.newConcurrentMap();
				}
			});

	/**
	 * 记录运行时间
	 * 
	 * @Description:
	 * @param label
	 * @param execTime
	 */
	public void recordExecTime(String type, String label, long execTime) {
		Assert.hasText(label);
		Assert.isTrue(execTime >= 0);

		final ConcurrentMap<String, ExecTimeRecord> debugInfoMap = debugInfoCache.getUnchecked(type);
		ExecTimeRecord debugInfo = debugInfoMap.get(label);
		if (debugInfo == null) {
			debugInfoMap.putIfAbsent(label, new ExecTimeRecord(label));
			debugInfo = debugInfoMap.get(label);
		}
		debugInfo.record(execTime);
	}

	@Override
	public JSONObject getDebugInfo() {
		JSONObject resultJson = new JSONObject();
		
		final ConcurrentMap<String, ConcurrentMap<String, ExecTimeRecord>> asMap = debugInfoCache.asMap();
		for (Map.Entry<String, ConcurrentMap<String, ExecTimeRecord>> entry : asMap.entrySet()) {
			List<ExecTimeRecord> tempList = Lists.newArrayList(entry.getValue().values());
			Collections.sort(tempList, new Comparator<ExecTimeRecord>() {
				public int compare(ExecTimeRecord o1, ExecTimeRecord o2) {
					Long count1 = Long.valueOf(o1.getTotalExecCount());
					Long count2 = Long.valueOf(o2.getTotalExecCount());

					// 按照接口调用次数逆序排序
					return count2.compareTo(count1);
				};
			});

			JSONObject jsonEntry = new JSONObject();
			jsonEntry.put("按照执行次数降序排", JSONArray.toJSON(tempList));

			Collections.sort(tempList, new Comparator<ExecTimeRecord>() {
				public int compare(ExecTimeRecord o1, ExecTimeRecord o2) {
					Long time1 = Long.valueOf(o1.getAvgExecTime());
					Long time2 = Long.valueOf(o2.getAvgExecTime());

					// 按照接口调用时间逆序排序
					return time2.compareTo(time1);
				};
			});

			jsonEntry.put("按照执行平均时间降序排", JSONArray.toJSON(tempList));
			
			resultJson.put(entry.getKey(), jsonEntry);
		}
		
		return resultJson;

	}

}
